<?php

namespace App\Models\Shop;

use Illuminate\Database\Eloquent\Model;
use JWTAuth;


class Cart extends Model
{
    protected $guarded = [];

    public function customer()
    {
        return $this->belongsTo('App\Models\Shop\Customer');
    }

    //购物车属于商品
    public function product()
    {
        return $this->belongsTo('App\Models\Shop\Product');
    }

    /***
     * 计算购物车数量和总价
     */
    static function count_cart()
    {
        $user = JWTAuth::parseToken()->authenticate();
        $count = [];
        $carts = Cart::with('product')->
        where('customer_id', $user->id)->get();

        $total_price = 0;
        $num = 0;
        foreach ($carts as $v) {
            $total_price += $v->product->price * $v->num;
            $num += $v->num;
        }
        $count['total_price'] = $total_price;
        $count['num'] = $num;
        return  $count;
    }

}
